<template>
	<delivery-finance-preview v-if="isConfirmApply" :mode="'order'"></delivery-finance-preview>
	<div v-else class="m-window" v-loading="pageLoading" element-loading-text="数据加载中">
		<!-- 订单融资申请 -->
		<el-row type="flex" class="applyShort-col">
			<el-col :span="12" class="financial">
				<label class="title">可融金额：</label>
				<div class="money">
					<sup>￥</sup>
					{{getFormatMoney}}
				</div>
			</el-col>
			<el-col :span="2" style="margin-top: 35px;">
				<el-button type="primary" @click="financing" :disabled="isBtnDisable" :loading="btnLoading">融资</el-button>
			</el-col>
			<el-tabs type="card" v-model="tabName" @tab-click="handleClick" class="orderlist-tabs">
				<el-tab-pane label="现可融订单记录" name="1">
					<ag-grid-vue
						class="ag-theme-balham ag-table"
						:gridOptions="orderGridOptions"
						:columnDefs="orderColumnDefs"
						:defaultColDef="defaultColDef"
						:rowData="orderRowData"
						v-loading="loading"
					></ag-grid-vue>
				</el-tab-pane>
				<el-tab-pane label="融资历史记录" name="2">
					<ag-grid-vue
						class="ag-theme-balham ag-table"
						:gridOptions="applyGridOptions"
						:columnDefs="applyColumnDefs"
						:defaultColDef="defaultColDef"
						:rowData="applyRowData"
						v-loading="loading"
					></ag-grid-vue>
					<pagination
						style="height:1%;"
						:config="{pageNumberChanged, pageSizeChanged, pageNumber: searchParams.pageNumber,pageSizes:[10, 30, 50, 100],justifyContent:'flex-end'}"
						:total="totalNum"
					></pagination>
				</el-tab-pane>
			</el-tabs>
			<!-- <div class="m-agTable m-top2 m-bottom history-table">
				<label>融资历史记录</label>
				<ag-grid-vue
					class="ag-theme-balham ag-table"
					:gridOptions="applyGridOptions"
					:columnDefs="applyColumnDefs"
					:defaultColDef="defaultColDef"
					:rowData="applyRowData"
					v-loading="loading"
				></ag-grid-vue>
				<pagination
					style="height:1%;"
					:config="{pageNumberChanged, pageSizeChanged, pageNumber: searchParams.pageNumber,pageSizes:[10, 30, 50, 100],justifyContent:'flex-end'}"
					:total="totalNum"
				></pagination>
			</div>-->
		</el-row>
		<!-- 查看订单详情弹窗 -->
		<el-dialog
			title="融资申请记录"
			:visible.sync="historyVisible"
			v-dialogDrag
			width="75%"
			class="order-detail-dialog"
		>
			<div class="historyRecord">
				<ag-grid-vue
					class="m-agTableModel ag-theme-balham"
					:gridOptions="historyGridOptions"
					:columnDefs="historyColumnDefs"
					:rowData="historyRowData"
					v-loading="historyLoading"
				></ag-grid-vue>
			</div>
			<span slot="footer" class="dialog-footer"></span>
		</el-dialog>
	</div>
</template>

<style lang="less" rel="stylesheet/less" scoped>
.applyShort-col {
	flex-direction: column;
	height: 100%;

	.financial {
		.title {
			color: #454545;
			font-size: 12px;
			font-weight: 600;
		}

		.money {
			color: #ff821f;
			font-size: 45px;
			font-weight: 600;

			sup {
				font-size: 22px;
			}
		}
	}
	.orderlist-tabs {
		margin-top: 20px;
		/deep/ .el-tabs__content {
			top: 220px;
			left: 0;
			right: 0;
			.ag-table {
				position: absolute;
				top: 0;
				bottom: 36px;
				left: 0;
				right: 0;
			}
			.pagination-box {
				position: absolute;
				bottom: 30px;
				right: 25px;
			}
		}
		/deep/ .el-tabs__item.is-top.is-active {
			background: #409eff;
			color: #fff;
		}
	}
	.history-table {
		margin-top: 35px;
		height: calc(100% - 240px);

		& label {
			font-size: 12px;
			font-weight: 600;
		}

		.ag-table {
			width: 100%;
			height: 99%;
			margin-top: 8px;
		}
	}

	.hint {
		color: red;
		font-size: 14px;
		font-weight: 600;
		font-family: "黑体";
	}
}
</style>

<script>
import {
	formatPrice,
	regainOriginalMoneyFormat
} from '@/util/format.js'
import addOperation from "@/public/addOperation";
import gridOptions from "lesso-common/public/gridOptions"
import Pagination from '@/components/pagination'
import buttonLink from "@/components/buttonLink"
import DeliveryFinancePreview from './common/deliveryFinancePreview'
import {
	mapState, mapActions
} from "vuex";
import Vue from "vue";
const toolTips = Vue.extend({
	template: `<div><el-tooltip class="item" effect="dark" :content="content" placement="right" v-if="flag==1">
      <span style="color:red">{{value}}</span>
    </el-tooltip>
    <span v-else>{{value}}</span>
    </div>`,
	data () {
		return {
			value: '',
			flag: 0,
			content: '经系统计算该订单可融资天数为0'
		};
	},
	mounted () {
		// flag=1时订单可融天数为0
		this.flag = this.params.data.flag
		if (!this.params.node.rowPinned) {
			this.value = new Date(this.params.value).Format("yyyy-MM-dd")
		}
	}
});
/**
 * @group financeManager
 * 金单宝融资申请
*/
export default {
	name: 'OrderFinance',
	data () {
		return {
			pageLoading: true,
			defaultColDef: {
				resizable: true
			},
			custId: this.$store.state.supplyChainFinance.custInf.custId, //获取供应商id
			isConfirmApply: false,
			searchParams: {
				pageNumber: 1
			},
			totalNum: 0,
			availableAmount: 0,
			applyGridOptions: {},
			applyColumnDefs: [],
			applyRowData: [],
			orderGridOptions: {},
			orderColumnDefs: [],
			orderRowData: [],
			loading: false,
			isBtnDisable: true,
			btnLoading: false,
			tabName: '1',
			totalAmount: {
				available: 0,
				already: 0
			},
			historyGridOptions: gridOptions(),
			historyColumnDefs: [],
			historyRowData: [],
			historyVisible: false,
			historyLoading: false,
			historyTotalAmount: 0
		}
	},
	props: {
		addTab: {
			type: Function
		}
	},
	beforeMount () {
		let params = {
			"condition": {
				"custId": this.custId
			},
			"current": 1,
			"size": 10
		}
		this.getOrderFinceOrderList(params);
		let amountParams = {
			'supplierId': this.custId
		}
		this.getAvailableAmount(amountParams);
	},
	created () {
		// this.getOneOrSave()
		this.applyGridOptions = gridOptions()
		this.orderGridOptions = {
			...gridOptions(),
			pinnedBottomRowData: this.createData(1, 'Bottom'),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { 'color': 'red', 'font-weight': "bold" }
				}
			},
			context: {
				componentParent: this
			},
		}
		// 订单融资历史记录表格配置
		this.historyGridOptions = {
			...gridOptions(),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { 'color': 'red', 'font-weight': "bold" }
				}
			},
			pinnedBottomRowData: this.createBottom(1, 'Bottom'),
		}
		// 现可融订单记录列配置
		this.orderColumnDefs = [
			{
				headerName: "采购订单号",
				field: "orderNumber",
				width: 140,
				cellRenderer: buttonLink,
			},
			{
				headerName: "订单金额",
				field: "orderMoney",
				width: 120,
				valueFormatter: params => {
					if (!params.node.rowPinned) {
						return formatPrice(params.value)
					}
				}
			},
			{
				headerName: "订单日期",
				field: "orderDate",
				width: 120,
				valueFormatter: params => {
					if (!params.node.rowPinned) {
						return this.$utils.dateFormat("yyyy-MM-dd", params.value)
					}
				}
			},
			{
				headerName: "最早约定交货日期",
				field: "oldestDeliveryDate",
				width: 160,
				cellRendererFramework: toolTips
			},
			{
				headerName: "已融资金额",
				field: "alreadyActBalance",
				width: 110,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "已融占比",
				field: "actBalancePart",
				width: 110
			},
			{
				headerName: "可融金额",
				field: "borrowBalance",
				width: 110,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "融资状态",
				field: "finStateDesc",
				width: 100,
			},
			{
				headerName: "订单状态",
				field: "billStateDesc",
				width: 100,
			},
		];
		// 历史融资变更列配置
		this.historyColumnDefs = [
			{
				headerName: "融资申请号",
				field: "itemNo",
				width: 140,
			},
			{
				headerName: "融资开始日期",
				field: "startDate",
				width: 140,
				valueFormatter: params => {
					if (!params.node.rowPinned && params.value) return this.$utils.dateFormat('yyyy-MM-dd', params.value)
				}
			},
			{
				headerName: "融资到期日期",
				field: "endDate",
				width: 140,
				valueFormatter: params => {
					if (!params.node.rowPinned && params.value) return this.$utils.dateFormat('yyyy-MM-dd', params.value)
				}
			},
			{
				headerName: "申请融资金额",
				field: "applyActAmount",
				width: 140,
				valueFormatter: params => {
					if (!params.node.rowPinned) return formatPrice(params.value)
				}
			},
			{
				headerName: "订单融资金额",
				field: "orderActAmount",
				width: 140,
				valueFormatter: params => {
					return formatPrice(params.value)
				}
			},
			{
				headerName: "申请状态",
				field: "statusDesc",
				width: 140,
				valueFormatter: (params) => {
					if (params.value) {
						return params.value == '供应商还款' ? '待还款' : params.value
					}
				},
			},
		]
		// 融资历史记录列配置
		this.applyColumnDefs = [{
			headerName: "序号",
			field: "xuhao",
			valueGetter: 'node.id',
			cellRenderer: function (params) {
				if (params.value != undefined) {
					return +params.value + 1;
				}
			}
		},
		{
			headerName: "申请编号",
			field: "itemNo"
		},
		{
			headerName: "融资开始日期",
			field: "payDate"
		},
		{
			headerName: "融资金额",
			field: "actAmt",
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		},
		{
			headerName: "已还款金额",
			field: "paybackAmount",
			valueFormatter: params => {
				return formatPrice(params.value)
			}
		},
		{
			headerName: "融资产品",
			field: "finType"
		},
		{
			headerName: "还款状态",
			field: "paybackProcessStatus"
		}
		]
	},
	computed: {
		...mapState(['supplyChainFinance', 'supplierApplyList']),
		getFormatMoney () {
			return formatPrice(this.availableAmount)
		},
		accountQuota () {
			return formatPrice(this.supplierApplyList.accountQuota)
		}
	},
	methods: {
		...mapActions(["changeAccountQuota"]),
        /**
		 * @vuese
		 * 点击tab标签回调
         * @arg 参数tab为当前tab标签编码
		*/
		handleClick (tab) {
			if (tab.name == '1') {
				this.getOrderFinceOrderList()
			} else if (tab.name == '2') {
				let params = {
					"condition": {
						"custId": this.custId
					},
					"current": 1,
					"size": 10
				}
				this.getOrderApplyHistoy(params);
			}
		},
        /**
		 * @vuese
		 * 获取订单融资所有已确认未融资订单
		*/
		getOrderFinceOrderList () {
			let params = {
				supplierId: this.custId,
				// state: 3
			}
			this.loading = true
			this.orderRowData = [];
			this.totalAmount.available = 0
			this.totalAmount.already = 0
			this.$http.getNoDeliveryOrders(params).then(({ data }) => {
				this.loading = false;
				if (data.code == 1) {
					let rowDatas = data.rows;
					this.orderRowData = rowDatas;
					if (this.orderRowData.length == 0) {
						this.orderGridOptions.overlayNoRowsTemplate = '未搜索到匹配结果'
					} else {
						this.orderRowData.forEach(item => {
							this.totalAmount.available = addOperation.accAdd(this.totalAmount.available, item.borrowBalance)
							this.totalAmount.already = addOperation.accAdd(this.totalAmount.already, item.alreadyActBalance)
						})
						this.orderGridOptions.api.setPinnedBottomRowData(this.createData(1, "Bottom"))
					}
				} else {
					this.orderRowData = [];
					this.orderGridOptions.overlayNoRowsTemplate = '未搜索到匹配结果'
				}
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg('查询订单列表数据失败!')
			})
		},
		/**
		 * @vuese
		 * 创建现可融资订单记录底部合计栏
         * @arg 参数count为行数，prefix合计栏位置
		*/
		createData (count, prefix) {
			let result = [];
			const { available, already } = this.totalAmount
			for (let i = 0; i < count; i++) {
				result.push({
					orderDate: "合计",
					alreadyActBalance: formatPrice(already),
					borrowBalance: formatPrice(available),
				})
			}
			return result;
		},
        /**
		 * @vuese
		 * 创建融资历史记录表格底部合计栏
         * @arg 参数count为行数，prefix合计栏位置
		*/
		createBottom (count, prefix) {
			let result = [];
			for (let i = 0; i < count; i++) {
				result.push({
					itemNo: "合计",
					orderActAmount: formatPrice(this.historyTotalAmount),
				})
			}
			return result;
		},
		/** 
         *@vuese 
         * 点击订单号回调获取订单融资申请记录 
         *@arg 参数是purOrdNo,订单号
	    */
		setClickValue (param) {
			// 获取订单变更信息
			let params = {
				purOrdNo: param.value
			}
			this.historyLoading = true
			this.historyRowData = []
			this.historyTotalAmount = 0
			this.$http.getOrderActAmountRecord(params).then(({ data }) => {
				this.historyLoading = false
				if (data.code == 1) {
					this.historyRowData = data.rows
					this.historyRowData.forEach(item => {
						this.historyTotalAmount = addOperation.accAdd(this.historyTotalAmount, item.orderActAmount)
					})
					this.historyGridOptions.api.setPinnedBottomRowData(this.createBottom(1, "Bottom"))
				} else {
					this.$alert(data.info, {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				}
			}).catch(err => {
				this.historyLoading = false
				this.$alert("获取数据失败！", {
					confirmButtonText: "确定",
					customClass: "alertFailure"
				});
			})
			this.historyVisible = true
		},

		/** 
		 *@vuese 
		 * 获取订单可融资额度
		*/
		getAvailableAmount (params) {
			let that = this
			this.$http.getOrderFinAmount(params).then((response) => {
				setTimeout(function () {
					that.pageLoading = false
				}, 500)
				if (response.data.code == 1) {
					this.availableAmount = response.data.rows.sumBorrowBalance ? response.data.rows
						.sumBorrowBalance : 0.00;
				} else {
					this.availableAmount = 0;
				}
				if (this.availableAmount > 0) {
					this.isBtnDisable = false
				}
			})
				.catch((errror) => {
					this.pageLoading = false
					this.$alert("查询可融金额失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				})
		},
        /** 
         *@vuese 
         * 获取融资历史记录表格数据
         *@arg 参数是params为接口查询参数
	    */
		getOrderApplyHistoy (params) {
			this.applyRowData = []
			this.loading = true
			this.$http.getOrderFinHistory(params).then((response) => {
				this.loading = false
				if (response.data.code == 200) {
					this.applyRowData = response.data.rows
					this.totalNum = response.data.total;
					let gridOption = this.applyGridOptions
					setTimeout(function () {
						let allColumnIds = []
						if (gridOption.columnApi) {
							gridOption.columnApi.getAllColumns().forEach(function (column) {
								allColumnIds.push(column.colId)
							})
							gridOption.columnApi.autoSizeColumns(allColumnIds)
						}
					})
				} else {
					this.applyRowData = []
					this.totalNum = 0;
				}
			})
				.catch((errror) => {
					this.$alert("查询融资历史记录失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				})
		},
        /** 
         *@vuese 
         * 点击融资按钮回调
        */
		financing () {
			if (this.availableAmount <= 0) {
				this.$alert("可融金额大于0才允许申请融资", {
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return
			} else {
				this.btnLoading = true
				this.changeAccountQuota({ supplierId: this.custId }).then(_ => {
					this.btnLoading = false
					// 存在对账融资额度时给出提示
					if (regainOriginalMoneyFormat(this.accountQuota) > 0) {
						this.$confirm(`系统检测已有天进宝融资额度,建议优先申请天进宝<br/>天进宝融资额度:&nbsp;&nbsp;<strong style="color:#ff821f">${this.accountQuota}</strong>`, '提示', {
							confirmButtonText: '前往天进宝',
							cancelButtonText: '继续申请金单宝',
							dangerouslyUseHTMLString: true,
							distinguishCancelAndClose: true,
							cancelButtonClass: "finceCancelClass",
							closeOnPressEscape: false,
							type: 'warning'
						}).then(() => {
							this.addTab(
								{
									cName: "天进宝",
									name: "applyShort",
									completed: false
								}
							)
						}).catch((action) => {
							if (action === 'cancel') this.isConfirmApply = true;
						});
					} else {
						this.isConfirmApply = true;
					}
				}).catch(err => {
					this.$alert(err, {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
					this.btnLoading = false
				})
			}
		},
        /** 
         *@vuese 
         * 页码改变回调
         * @arg 参数为当前页码
        */
		pageNumberChanged (pageNum) {
			if (pageNum) {
				let params = {
					"condition": {
						"custId": this.custId
					},
					"current": pageNum,
					"size": 10
				}
				this.getOrderApplyHistoy(params);
			}
		},
		/** 
         *@vuese 
         * 每页显示条数改变回调
         * @arg 参数为当前显示条数
	   */
		pageSizeChanged (pageSize) {
			if (pageSize) {
				let params = {
					"condition": {
						"custId": this.custId
					},
					"current": 1,
					"size": pageSize
				}
				this.getOrderApplyHistoy(params);
			}
		},
		//获取客户表详情,若没有则新增
		// async getOneOrSave() {
		//     let params = this.supplyChainFinance.custInf2
		//     let that = this
		//     await that.$http.getOneOrSave(params).then(({
		//             data
		//         }) => {
		//             if (data.code == 200 && data.rows) {
		//                 //'融资状态:0-未融资,1-在天进宝  2-在月有钱'
		//                 //that.isAllowFinancing = data.rows.finStatus <= 1 ? true:false
		//             } else {
		//                 that.$alert("获取新增客户信息失败:" + data.info, {
		//                     confirmButtonText: "确定",
		//                     customClass: "alertFailure"
		//                 })
		//             }
		//         })
		//         .catch((errror) => {
		//             that.$alert("查询客户表，请检查网络！", {
		//                 confirmButtonText: "确定",
		//                 customClass: "alertFailure"
		//             })
		//         })
		// }
	},
	components: {
		Pagination,
		DeliveryFinancePreview
	}
}
</script>